<?php

namespace app\admin\controller\user\payment;

use app\admin\model\HouseModel;
use app\common\controller\Backend;
use app\common\model\OrderPaymentRecords;
use think\Db;

/**
 * 用户缴费记录
 *
 * @icon fa fa-circle-o
 */
class Records extends Backend
{

    /**
     * Records模型对象
     * @var \app\admin\model\user\payment\Records
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\user\payment\Records;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $diy_where = [];
            if (!$this->auth->isSuperAdmin()) {
                $diy_where['contract.id'] = ['in', function ($query) {
                    $house_ids = HouseModel::withTrashed()->where('community', $this->auth->manage_community)->column('id');
                    $query->name('user_contract')->where('house_id', 'in', $house_ids)->field('id');
                }];
            }
            $list = $this->model
                    ->with(['user','homeowner','contract','orders'])
                    ->where($where)
                    ->where($diy_where)
                    ->order($sort, $order)
                    ->paginate($limit);
//            echo $this->model->getLastSql();die;
            $type=1;
            foreach ($list as $row) {
                $type=$row['type'];

            }

            $result = array("total" => $list->total(), "rows" => $list->items());
            $status=$type==1?false:true;
            $this->assignconfig('show_status',$status);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 结算
     *
     * @param $ids
     * @return void
     */
    public function jie($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        $tableAlias = 'p'; // 定义表别名

        if (is_array($adminIds)) {
            // 明确指定表别名
            $this->model->where("{$tableAlias}.{$this->dataLimitField}", 'in', $adminIds);
        }
        if ($ids) {
            // 明确指定表别名
            $this->model->where("{$tableAlias}.{$pk}", 'in', $ids);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->alias($tableAlias)
                ->join('user_order_payment_records o','o.other_id=p.id')
                ->whereIn("{$tableAlias}.id", $ids)
                ->where(['o.status'=>1,'o.pay_type'=>1])
                ->update(["{$tableAlias}.jie_status"=>1,"{$tableAlias}.updatetime"=>time()]);
//            dump($list);die;

            if ($list === false) {
                Db::rollback();
                $this->error('处理失败');
            } else {
                $count = $list; // 更新受影响的记录数
                Db::commit();
            }

        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

    /**
     * 退款
     *
     * @param $ids
     * @return void
     */
    public function tui($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        $tableAlias = 'p'; // 定义表别名

        if (is_array($adminIds)) {
            // 明确指定表别名
            $this->model->where("{$tableAlias}.{$this->dataLimitField}", 'in', $adminIds);
        }
        if ($ids) {
            // 明确指定表别名
            $this->model->where("{$tableAlias}.{$pk}", 'in', $ids);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->alias($tableAlias)
                ->join('user_order_payment_records o','o.other_id=p.id')
                ->whereIn("{$tableAlias}.id", $ids)
                ->where(['o.status'=>1,'o.pay_type'=>1])
                ->update(["o.tui_status"=>1,"o.updatetime"=>time()]);

            if ($list === false) {
                Db::rollback();
                $this->error('处理失败');
            } else {
                $count = $list; // 更新受影响的记录数
                Db::commit();
            }

        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

}
